package sgd.tp2.server.net.udp;

import java.io.IOException;
import java.net.DatagramPacket;

import sgd.tp2.api.cdr.CDR;
import sgd.tp2.api.cdr.CDRHandlerCSV;
import sgd.tp2.api.logging.Log;
import sgd.tp2.api.net.CDRFormatType;
import sgd.tp2.api.net.CEPType;

public class UDPServerCSV extends UDPServer {

	public UDPServerCSV(CDRFormatType cdrFormatType, CEPType cepType, int port) {
		super(cdrFormatType, port, cepType);
	}

	public UDPServerCSV(CDRFormatType cdrFormatType, int port, CEPType cepType, int packetSize) {
		super(cdrFormatType, port, cepType, packetSize);
	}

	@Override
	public void run() {

		byte[] receivedData = new byte[packetSize];
		DatagramPacket packet = new DatagramPacket(receivedData, receivedData.length);

		while (running) {

			// Esperar mensagem
			try {
				serverSocket.receive(packet);
				
				receivedCDR();

			} catch (IOException e) {
				Log.infoln("");
				Log.warningln("Parou de receber. Servidor terminado");
				stopServer();
				break;
			}

			handleCSV(packet);
		}
	}

	public void handleCSV(DatagramPacket packet) {
		startCDRHandling();

		String csv = new String(packet.getData(), packet.getOffset(), packet.getLength());
		CDR cdr = CDRHandlerCSV.getCDRFromCSV(csv);
		handleCDR(cdr);

		endCDRHandling(cdr);
	}
}
